package com.linxi.wordslog.wordslogviewmodel

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson
import com.linxi.wordslog.VolleySingleton
import com.linxi.wordslog.data.Result
import com.linxi.wordslog.data.TranslateResult
import java.lang.Exception

class AddWordViewModel(application: Application) : AndroidViewModel(application) {
    private val _addWordListLiveData = MutableLiveData<List<Result>>()
    val addWordListLiveData = _addWordListLiveData

    private fun getUrl(key: String) =
        "https://fanyi.youdao.com/translate?&doctype=json&type=AUTO&i=$key"

    fun fetchData(key: String) {
        StringRequest(
            Request.Method.GET,
            getUrl(key),
            Response.Listener {
                val translateResult = Gson().fromJson(it, TranslateResult::class.java)
                val results = translateResult.translateResult[0]
                _addWordListLiveData.value = results
                Log.d("hello", "fetchData: ${results.size}")
            },
            Response.ErrorListener {
                Log.d("hello", "fetchData: $it")
            }
        ).also {
            VolleySingleton.getInstance(getApplication()).queue.add(it)
        }
    }
}